//
//  TrianDataBaseHandel.m
//  LiTingFeng
//
//  Created by xinxuan on 16/3/4.
//  Copyright © 2016年 Bullgo. All rights reserved.
//

#import "TrianDataBaseHandel.h"
#import "FMDatabase.h"
#import "DataModel.h"

@interface TrianDataBaseHandel()<NSCopying>
{
    FMDatabase *_db;
}

@end
@implementation TrianDataBaseHandel

static id _instace;
+(instancetype)shareManager
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instace = [[self alloc] init];
    });
    return _instace;
}



-(id)copyWithZone:(NSZone *)zone
{
    return _instace;
}


+(instancetype)allocWithZone:(struct _NSZone *)zone
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instace = [super allocWithZone:zone];
    });
    return _instace;
}

-(id)init
{
    self = [super init];
    if (self) {
        
        NSString *path = [NSHomeDirectory() stringByAppendingString:@"/Documents/LiTingFeng.db"];
        NSLog(@"DB Path%@",path);
        //创建并打开
        _db = [FMDatabase databaseWithPath:path];
        if ([_db open]) {
            NSLog(@"创建成功");
            //打开成功
            NSString *sql = @"create table trainData(name  text primary key not NULL ,starCount INTEGER not NULL,centent text not NULL,period text not NULL,growth text not NULL,time text not NULL,useNumber INTEGER not NULL,cycle INTEGER not NULL)";
            BOOL isSuccess = [_db executeUpdate:sql];
            if (!isSuccess) {
                NSLog(@"创建表失败:%@~~~",_db.lastErrorMessage);
            }
        }else
        {
            NSLog(@"创建数据库或打开失败");
        }
    }
    return self;
}



//写入数据
-(void)insertData:(id)object{
    
    if ([object isKindOfClass:[CommenModel class]]) {
        
        CommenModel * model = (CommenModel *)object;
        
        if ([self selectNewsTitle:model.name]) {
            return;
        }else{
        
        
        if ([_db open]) {
            
            NSString *insertSql= [NSString stringWithFormat:@"INSERT INTO trainData (name, starCount, centent,period,growth,time,useNumber,cycle) VALUES ('%@', '%lu','%@','%@','%@','%@', '%lu','%lu')",model.name, (long)[model.starCount integerValue] ,model.centent,model.period,model.growth,model.time,(unsigned long)model.useNumber,(unsigned long)model.cycle];
            
            BOOL isSuccess = [_db executeUpdate:insertSql];
            
            if (!isSuccess) {
                NSLog(@"error when insert db table");
            } else {
                NSLog(@"success to insert db table");
            }
            
            [_db close];
            
            
        }
    }
    }
    
    
    
    
}







//读取数据
-(NSMutableArray *)fetchAllData
{
    NSMutableArray *videoDataArray = [NSMutableArray array];
    
    if ([_db open]) {
        NSString *sql = @"select * from trainData";
        FMResultSet *set = [_db executeQuery:sql];
        while ([set next]) {
            NSString *name = [set stringForColumn:@"name"];
            NSUInteger starCount = [set longForColumn:@"starCount"];
            NSString *centent = [set stringForColumn:@"centent"];
            NSString *period = [set stringForColumn:@"period"];
            NSString *growth = [set stringForColumn:@"growth"];
            NSString *time = [set stringForColumn:@"time"];
            NSUInteger useNumber = [set longForColumn:@"useNumber"];
            NSUInteger cycle = [set longForColumn:@"cycle"];
            
            CommenModel *model = [[CommenModel alloc]init];
            model.name = name;
            model.starCount = [NSString stringWithFormat:@"%ld",(unsigned long)starCount];
            model.centent = centent;
            model.period = period;
            model.growth = growth;
            model.time = time;
            model.useNumber = useNumber ;
            model.cycle = cycle;
            
            [videoDataArray addObject:model];
        }
        [_db close];
    }
    return videoDataArray;
    
    
}


#pragma mark - 判断title是否已经存储过
- (BOOL)selectNewsTitle:(NSString*)name
{
    if ([_db open]) {
        NSString *sql = [NSString  stringWithFormat: @"select * from trainData where name = '%@'",name ];
        FMResultSet *set = [_db executeQuery:sql];
        while ([set next]) {
            NSString *nameString = [set stringForColumn:@"name"];
            if ([nameString isEqualToString:name]) {
                return YES;
            }
            
            
        }
        [_db close];
    }
    return NO;
}


//根据课程名，查找数据
-(CommenModel*)fetchDataWithName:(NSString*)name{
    CommenModel *model = [[CommenModel alloc]init];
    
    if ([_db open]) {
        NSString *sql = [NSString  stringWithFormat: @"select * from trainData where name = '%@'",name ];
        FMResultSet *set = [_db executeQuery:sql];
        while ([set next]) {
            NSString *nameString = [set stringForColumn:@"name"];
            NSUInteger starCount = [set longForColumn:@"starCount"];
            
            model.name = nameString;
            model.useNumber = starCount;
           
        }
        [_db close];
    }
    return model;
    
}


//读取课程名
-(NSMutableArray *)fetchAllName
{
    NSMutableArray *nameArray = [NSMutableArray array];
    if ([_db open]) {
        NSString *sql = @"select * from trainData";
        FMResultSet *set = [_db executeQuery:sql];
        while ([set next]) {
            NSString *name = [set stringForColumn:@"name"];
            
            [nameArray addObject:name];
        }
        [_db close];
    }
    return nameArray;
}

//删除数据
-(void)deleteData:(id)object{
    // 4  删除数据
    if ([object isKindOfClass:[CommenModel class]]) {
        CommenModel *model = (CommenModel *)object;
        NSString * deleteSql = [NSString stringWithFormat:@"delete from %@ where %@ = '%@'",@"trainData" ,@"name",model.name];
        BOOL res = [_db executeUpdate:deleteSql];
        
        if (res) {
            NSLog(@"修改数据成功");
        }
        else
        {
            NSLog(@"修改数据失败");
        }
        
    }
    
    
    
}


@end
